package server

import (
	"flag"
	"fmt"
	"github.com/disintegration/imaging"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"slices"
	"strings"
)

func Run() {

	var port string
	var token string
	flag.StringVar(&port, "port", "8080", "Server port")
	flag.StringVar(&token, "token", "admin", "Token")
	flag.Parse()

	r := gin.Default()
	os.MkdirAll("./img", 0777)
	r.Static("/img", "./img")
	r.POST("/upload", func(c *gin.Context) {
		if c.GetHeader("token") != token {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
			return
		}
		ext := c.Query("type")
		if !slices.Contains([]string{"png", "jpg", "jpeg"}, ext) {
			c.JSON(http.StatusBadRequest, gin.H{"error": "invalid type"})
			return
		}
		body, err := io.ReadAll(c.Request.Body)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		defer c.Request.Body.Close()
		name := fmt.Sprintf("%s.%s", uuid.New().String(), ext)
		path := fmt.Sprintf("./img/%s", name)
		err = os.WriteFile(path, body, 0777)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		go ImageZip(path)
		path = strings.TrimPrefix(path, ".")
		c.JSON(http.StatusOK, gin.H{"name": name})
	})
	err := r.Run(":" + port)
	if err != nil {
		log.Fatal(err)
	}
}

func ImageZip(path string) {
	//打开原始图片
	img, err := imaging.Open(path)
	if err != nil {
		log.Printf("图片压缩打开失败%v", err)
		return
	} // 压缩图片

	width := img.Bounds().Dx()
	height := img.Bounds().Dy()

	// 计算压缩后的尺寸（保持宽高比）
	var newWidth, newHeight int
	if width > 800 {
		newWidth = 800
		newHeight = (height * 800) / width
	} else {
		newWidth = width
		newHeight = height
	}

	compressedImg := imaging.Resize(img, newWidth, newHeight, imaging.Lanczos)

	// 保存压缩后的图片为 JPG 格式
	compressedPath, _ := filepath.Abs(path + "_2s.jpg")
	compressedFile, err := os.Create(compressedPath)
	if err != nil {
		log.Println(err)
		return
	}
	defer compressedFile.Close()

	// 将压缩后的图片写入文件，固定为 JPG 格式
	if err := imaging.Encode(compressedFile, compressedImg, imaging.JPEG); err != nil {
		log.Println(err)
		return
	}
	log.Println("压缩成功：", path)
}
